#include <bits/stdc++.h>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head!=NULL && head->val == val){
            ListNode *new_head = head->next;
            delete head;
            head = new_head;
        }

        if(head == NULL) return head;
        ListNode *p = head;
        while(p->next != NULL){
            if(p->next->val == val){
                ListNode *delete_node = p->next;
                p->next = delete_node->next;
                delete delete_node;
            }
            p = p->next;
        }
        return head;
    }
};